<template>
  <div class="chart-settings">
    <a-form layout="vertical">
      <!-- 图表标题设置 -->
      <a-form-item label="标题">
        <a-input v-model:value="localOptions.title.text" placeholder="请输入图表标题" />
      </a-form-item>
      
      <a-form-item label="显示标题">
        <a-switch v-model:checked="localOptions.title.show" />
      </a-form-item>
      
      <!-- 饼图设置 -->
      <a-divider>饼图设置</a-divider>
      
      <a-form-item label="显示图例">
        <a-switch v-model:checked="localOptions.legend.show" />
      </a-form-item>
      
      <a-form-item label="图例位置" v-if="localOptions.legend.show">
        <a-radio-group v-model:value="localOptions.legend.orient">
          <a-radio-button value="horizontal">水平</a-radio-button>
          <a-radio-button value="vertical">垂直</a-radio-button>
        </a-radio-group>
      </a-form-item>
      
      <a-form-item label="图例位置" v-if="localOptions.legend.show">
        <a-select v-model:value="localOptions.legend.left">
          <a-select-option value="left">左侧</a-select-option>
          <a-select-option value="center">居中</a-select-option>
          <a-select-option value="right">右侧</a-select-option>
        </a-select>
      </a-form-item>
      
      <a-form-item label="饼图半径">
        <a-input-number 
          v-model:value="pieRadius" 
          :min="30" 
          :max="100"
          :formatter="(value: number) => `${value}%`"
          :parser="(value: string) => value.replace('%', '')"
          @change="updatePieRadius"
        />
      </a-form-item>
      
      <a-form-item label="是否为环形图">
        <a-switch v-model:checked="isDonut" @change="updatePieRadius" />
      </a-form-item>
      
      <a-form-item label="内环半径" v-if="isDonut">
        <a-input-number 
          v-model:value="innerRadius" 
          :min="0" 
          :max="pieRadius - 10"
          :formatter="(value: number) => `${value}%`"
          :parser="(value: string) => value.replace('%', '')"
          @change="updatePieRadius"
        />
      </a-form-item>
      
      <a-form-item label="系列名称">
        <a-input v-model:value="localOptions.series[0].name" placeholder="请输入系列名称" @change="emitUpdate" />
      </a-form-item>
      
      <!-- 数据项设置 -->
      <a-divider>数据项</a-divider>
      
      <div v-for="(item, index) in localOptions.series[0].data" :key="index" class="data-item">
        <a-row :gutter="[16, 0]">
          <a-col :span="10">
            <a-form-item :label="`名称 ${index + 1}`">
              <a-input v-model:value="item.name" placeholder="请输入名称" @change="emitUpdate" />
            </a-form-item>
          </a-col>
          <a-col :span="10">
            <a-form-item :label="`数值 ${index + 1}`">
              <a-input-number 
                v-model:value="item.value" 
                style="width: 100%"
                @change="emitUpdate"
              />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label=" " class="delete-btn-container">
              <a-button 
                type="primary" 
                danger 
                @click="removeDataItem(index)"
                shape="circle"
              >
                <delete-outlined />
              </a-button>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item :label="`自定义颜色 ${index + 1}`">
          <a-input 
            :value="getItemColor(index)" 
            placeholder="如: #1890ff" 
            :addon-before="'颜色'"
            @change="(e: Event) => updateItemColor(index, (e.target as HTMLInputElement).value)"
          />
        </a-form-item>
      </div>
      
      <a-divider></a-divider>
      
      <a-button type="dashed" block @click="addDataItem">
        <plus-outlined /> 添加数据项
      </a-button>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';

const props = defineProps({
  options: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['update:options']);

// 本地存储options，用于编辑
const localOptions = ref<any>({
  title: {
    text: '',
    show: false
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    show: true,
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '访问来源',
      type: 'pie',
      radius: '50%',
      data: [
        { value: 1048, name: '搜索引擎' },
        { value: 735, name: '直接访问' },
        { value: 580, name: '邮件营销' },
        { value: 484, name: '联盟广告' },
        { value: 300, name: '视频广告' }
      ]
    }
  ],
  color: [] // 自定义颜色
});

// 饼图半径
const pieRadius = ref(50);
const isDonut = ref(false);
const innerRadius = ref(30);

// 获取数据项颜色
const getItemColor = (index: number) => {
  if (localOptions.value.color && localOptions.value.color[index]) {
    return localOptions.value.color[index];
  }
  return '';
};

// 更新数据项颜色
const updateItemColor = (index: number, color: string) => {
  if (!localOptions.value.color) {
    localOptions.value.color = [];
  }
  
  // 确保数组长度足够
  while (localOptions.value.color.length <= index) {
    localOptions.value.color.push('');
  }
  
  localOptions.value.color[index] = color;
  emitUpdate();
};

// 更新饼图半径
const updatePieRadius = () => {
  if (isDonut.value) {
    localOptions.value.series[0].radius = [
      `${innerRadius.value}%`,
      `${pieRadius.value}%`
    ];
  } else {
    localOptions.value.series[0].radius = `${pieRadius.value}%`;
  }
  emitUpdate();
};

// 添加数据项
const addDataItem = () => {
  localOptions.value.series[0].data.push({
    value: 0,
    name: `新数据项${localOptions.value.series[0].data.length + 1}`
  });
  emitUpdate();
};

// 移除数据项
const removeDataItem = (index: number) => {
  localOptions.value.series[0].data.splice(index, 1);
  
  // 同时更新颜色数组
  if (localOptions.value.color && localOptions.value.color.length > index) {
    localOptions.value.color.splice(index, 1);
  }
  
  emitUpdate();
};

// 初始化
onMounted(() => {
  // 深拷贝props的options
  if (props.options) {
    localOptions.value = JSON.parse(JSON.stringify(props.options));
    
    // 确保必要的属性存在
    if (!localOptions.value.title) {
      localOptions.value.title = { text: '', show: false };
    }
    
    if (!localOptions.value.legend) {
      localOptions.value.legend = { show: true, orient: 'vertical', left: 'left' };
    } else {
      localOptions.value.legend.show = localOptions.value.legend.show !== false;
    }
    
    if (!localOptions.value.series || !localOptions.value.series.length) {
      localOptions.value.series = [{
        name: '数据系列',
        type: 'pie',
        radius: '50%',
        data: []
      }];
    }
    
    // 初始化半径设置
    const radius = localOptions.value.series[0].radius;
    if (Array.isArray(radius)) {
      isDonut.value = true;
      innerRadius.value = parseInt(radius[0], 10) || 30;
      pieRadius.value = parseInt(radius[1], 10) || 50;
    } else if (typeof radius === 'string') {
      isDonut.value = false;
      pieRadius.value = parseInt(radius, 10) || 50;
    }
  }
});

// 向父组件发送更新的options
const emitUpdate = () => {
  emit('update:options', localOptions.value);
};

// 监听props.options变化
watch(() => props.options, (newOptions) => {
  if (newOptions) {
    localOptions.value = JSON.parse(JSON.stringify(newOptions));
    
    // 重新初始化半径设置
    const radius = localOptions.value.series[0].radius;
    if (Array.isArray(radius)) {
      isDonut.value = true;
      innerRadius.value = parseInt(radius[0], 10) || 30;
      pieRadius.value = parseInt(radius[1], 10) || 50;
    } else if (typeof radius === 'string') {
      isDonut.value = false;
      pieRadius.value = parseInt(radius, 10) || 50;
    }
  }
}, { deep: true });
</script>

<style scoped>
.chart-settings {
  padding: 10px;
}

.data-item {
  padding: 10px;
  margin-bottom: 12px;
  border: 1px dashed #ddd;
  border-radius: 4px;
}

.delete-btn-container {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  height: 100%;
}
</style> 